package com.yuji.aacar.widgets.loading;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.yuji.aacar.utils.Util;


/**
 * <li>Package: {@link LoadPointView}
 * <li>Date: 2017/4/14 15:21
 * <li>Discription: 加载框中的三个点
 */

public class WLoadPointView extends View implements Runnable {
    private int color = Color.WHITE;//圆的颜色
    private float radiusBig;//大圆半径
    private float radiusSmall;//小圆半径
    private float circleBetween;//圆心之间的间隔
    private Paint paint;
    private int circleCount = 3;//点的个数
    private int bigCirclePosition = -1;//当前哪个是大圆

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    public WLoadPointView(Context context) {
        super(context);
        init();
    }

    public WLoadPointView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public WLoadPointView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        paint = new Paint();
        paint.setColor(color);
        paint.setAntiAlias(true);

        radiusBig = Util.dip2px(getContext(), 3.5f);
        radiusSmall = Util.dip2px(getContext(), 3f);
        circleBetween = Util.dip2px(getContext(), 15f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        bigCirclePosition = bigCirclePosition == circleCount - 1 ? 0 : bigCirclePosition + 1;
        for (int i = 0; i < circleCount; i++) {
            if (bigCirclePosition == i) {
                canvas.drawCircle(i * circleBetween + radiusBig, radiusBig, radiusBig, paint);
            } else {
                canvas.drawCircle(i * circleBetween + radiusBig, radiusBig, radiusSmall, paint);
            }

        }
        handler.postDelayed(this, 400);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacks(this);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) Math.ceil(((circleBetween + radiusBig) * (circleCount - 1))), MeasureSpec.EXACTLY);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) Math.ceil((radiusBig * 2)), MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public void run() {
        invalidate();
    }
}
